package com.ruoyi.business.base;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页 入参
 *
 * @author JYL
 * @date 2022/6/18 15:46
 */
@Data
public class PageParam
{

    private String keyword;
    private String startTime;
    private String endTime;
    private String sortKey;
    private boolean sort;
    private String sortKeyValues;
    /**
     * 通配 页码 数量
     */
    private Integer current = 1;
    private Integer size = 10;

    /**
     * 当前项目 页码 数量
     */
    private Integer pageNum = 1;
    private Integer pageSize = 10;
    /**
     * 入参格式[{},{}]jsonArray;
     * <hr>
     * 例子:[{"column":"create_time","asc":true}]
     */
    private String orders;

    private List<Long> ids;

    public PageParam()
    {
    }

    public Integer getCurrent()
    {
        return pageNum;
    }

    public Integer getSize()
    {
        return pageSize;
    }

    public PageParam(Integer size)
    {
        this.size = size;
    }

    public List<OrderItem> generateOrderList()
    {
        List<OrderItem> orderItemList = new ArrayList<>();
        try
        {
            orderItemList = JSONArray.parseArray(orders, OrderItem.class);
        } catch (Exception e)
        {

        }
        return orderItemList;
    }

    public <K> IPage<K> buildPage()
    {
        Page<K> page = new Page<>(getCurrent(), getSize());
        if (StringUtils.isNotBlank(orders))
        {
            page.addOrder(generateOrderList());
        }
        return page;
    }

    /**
     * 构建 分页对象 (糖块)
     *
     * @param <K>
     * @return
     */
    public <K> IPage<K> b()
    {
        return buildPage();
    }

    public PageParam setKeyword(String keyword)
    {
        this.keyword = keyword;
        return this;
    }

    /**
     * 补充时分秒格式
     *
     * @return
     */
    public String getStartTimeBuilder()
    {
        if (StringUtils.isBlank(this.startTime))
        {
            return null;
        }
        if (this.startTime.length() != 10)
        {
            return this.startTime;
        }
        //长度是10表示是天的格式，没有时分秒，补充时分秒
        return this.startTime + " 00:00:00";
    }

    /**
     * 补充时分秒格式
     *
     * @return
     */
    public String getEndTimeBuilder()
    {
        if (StringUtils.isBlank(this.endTime))
        {
            return null;
        }
        if (this.endTime.length() != 10)
        {
            return this.endTime;
        }
        //长度是10表示是天的格式，没有时分秒，补充时分秒
        return this.endTime + " 23:59:59";
    }

}
